package cn.xawl.gulimall.product.service.impl;

import cn.xawl.common.constant.ProductConstant;
import cn.xawl.common.to.MemberPriceTo;
import cn.xawl.common.to.SkuFullReductionTo;
import cn.xawl.common.to.SkuLadderTo;
import cn.xawl.common.to.SpuBoundTo;
import cn.xawl.common.to.es.SkuEsModel;
import cn.xawl.common.utils.PageUtils;
import cn.xawl.common.utils.Query;
import cn.xawl.common.utils.R;
import cn.xawl.common.vo.SkuHasStockVo;
import cn.xawl.gulimall.product.dao.SpuInfoDao;
import cn.xawl.gulimall.product.entity.*;
import cn.xawl.gulimall.product.feign.CouponFeign;
import cn.xawl.gulimall.product.feign.SearchFeign;
import cn.xawl.gulimall.product.feign.WareFeign;
import cn.xawl.gulimall.product.service.*;
import cn.xawl.gulimall.product.vo.spuvo.*;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Transactional
@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private ProductAttrValueService spuAttrValueService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuAttrService;

    @Autowired
    private CouponFeign couponFeign;

    @Autowired
    private WareFeign wareFeign;

    @Autowired
    private SearchFeign searchFeign;

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();

        /*
         *    key: '华为',//检索关键字
         *    catalogId: 6,//三级分类id
         *    brandId: 1,//品牌id
         *    status: 0,//商品状态
         */
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and(w -> {
                w.eq("id", key).or().like("spu_name", key);
            });
        }

        String catalogId = (String) params.get("catalogId");
        if (!StringUtils.isEmpty(catalogId) && Integer.parseInt(catalogId) > 0) {
            wrapper.eq("catalog_id", catalogId);
        }

        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId)) {
            wrapper.eq("brand_id", brandId);
        }

        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status) && status.contains("012")) {
            wrapper.eq("publish_status", status);
        }


        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }


    @Override
    public void saveSpu(SpuInfoVo spuInfoVo) {
        //先保存spu的基本信息
        SpuInfoEntity spuBaseInfo = new SpuInfoEntity();
        BeanUtils.copyProperties(spuInfoVo, spuBaseInfo);
        spuBaseInfo.setCreateTime(new Date());
        spuBaseInfo.setUpdateTime(new Date());
        this.baseMapper.insert(spuBaseInfo);


        Long spuId = spuBaseInfo.getId();

        //保存spu信息介绍  describe ==>pms_spu_info_desc
        SpuInfoDescEntity spuInfoDesc = new SpuInfoDescEntity();
        List<String> describe = spuInfoVo.getDescribe();

        spuInfoDesc.setSpuId(spuId);
        spuInfoDesc.setIntroduce(String.join(",", describe));
        spuInfoDescService.save(spuInfoDesc);

        //保存图片  images==》pms_spu_images
        //获取视图对象中的图片列表
        List<String> spuImages = spuInfoVo.getImages();
        if (!CollectionUtils.isEmpty(spuImages)) {
            List<SpuImagesEntity> spuImgList = spuImages.stream().map(spuImg -> {
                //创建spu图片对象
                SpuImagesEntity spuImage = new SpuImagesEntity();
                //对图片对象进行赋值
                spuImage.setSpuId(spuId);
                //将图片列表转换称一个土拍你字符串，用逗号隔开
                spuImage.setImgUrl(spuImg);
                return spuImage;
            }).collect(Collectors.toList());
            spuImagesService.saveBatch(spuImgList);
        }


        //保存spu的基础属性信息 baseAttrs==》pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuInfoVo.getBaseAttrs();
        List<ProductAttrValueEntity> spuAttrs = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity spuAttrValue = new ProductAttrValueEntity(); //创建spu基础属性的对象
            spuAttrValue.setAttrId(attr.getAttrId());
            //根据spuAttrId查询attrName
            AttrEntity attrEntity = attrService.getById(attr.getAttrId());
            if (attrEntity != null) {
                spuAttrValue.setAttrName(attrEntity.getAttrName());
            }
            spuAttrValue.setSpuId(spuId);
            spuAttrValue.setAttrValue(attr.getAttrValues());
            spuAttrValue.setQuickShow(attr.getShowDesc());
            return spuAttrValue;
        }).collect(Collectors.toList());
        spuAttrValueService.saveBatch(spuAttrs);

        //保存商品spu积分  bounds ==》 sms_spu_bounds
        Bounds spuBounds = spuInfoVo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(spuBounds, spuBoundTo);
        spuBoundTo.setSpuId(spuId);
        couponFeign.saveSpuBound(spuBoundTo);


        //保存sku信息 skus ==> pms_sku_info
        List<Skus> skus = spuInfoVo.getSkus();
        if (!CollectionUtils.isEmpty(skus)) {
            SkuInfoEntity skuBaseInfo = new SkuInfoEntity();
            skus.forEach(sku -> {
                //复制相同名字的属性
                BeanUtils.copyProperties(sku, skuBaseInfo);
                //定义不同名字的属性
                skuBaseInfo.setSpuId(spuId);
                skuBaseInfo.setBrandId(spuInfoVo.getBrandId());
                skuBaseInfo.setCatalogId(spuInfoVo.getCatalogId());
                skuBaseInfo.setSaleCount(0L);


                List<Images> images = sku.getImages();
                if (!CollectionUtils.isEmpty(images)) {
                    images.forEach(img -> {
                        if (img.getDefaultImg() == 1) {
                            skuBaseInfo.setSkuDefaultImg(img.getImgUrl());
                        }
                    });
                    skuInfoService.save(skuBaseInfo);

                    Long skuId = skuBaseInfo.getSkuId();

                    //保存sku的image实体 ==》 pms_sku_images
                    List<SkuImagesEntity> imagesEntityList = images.stream().map(img -> {
                        //由于提交时其他没有选中的图片也会进行提交，这里进行判断，如果当前的图片没有url，那么就不进行保存
                        if (!StringUtils.isEmpty(img.getImgUrl())) {
                            return null;
                        } else {
                            SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                            skuImagesEntity.setDefaultImg(img.getDefaultImg());
                            skuImagesEntity.setImgUrl(img.getImgUrl());
                            skuImagesEntity.setSkuId(skuId);
                            return skuImagesEntity;
                        }
                    }).collect(Collectors.toList());
                    imagesEntityList.forEach(imagesEntity -> {
                        if (imagesEntity != null) {
                            skuImagesService.save(imagesEntity);
                        }
                    });

                    //保存商品的销售属性（sku的属性）
                    List<Attr> skuAttr = sku.getAttr();
                    List<SkuSaleAttrValueEntity> saleAttrList = skuAttr.stream().map(attr -> {
                        SkuSaleAttrValueEntity saleAttr = new SkuSaleAttrValueEntity();
                        BeanUtils.copyProperties(attr, saleAttr);
                        saleAttr.setSkuId(skuBaseInfo.getSkuId());
                        return saleAttr;
                    }).collect(Collectors.toList());
                    skuAttrService.saveBatch(saleAttrList);

                    //保存sku满减信息
                    SkuFullReductionTo skuFullReductionTo = new SkuFullReductionTo();
                    skuFullReductionTo.setSkuId(skuId);
                    skuFullReductionTo.setFullPrice(sku.getFullPrice());
                    skuFullReductionTo.setReducePrice(sku.getReducePrice());
                    skuFullReductionTo.setAddOther(sku.getPriceStatus());
                    if (sku.getReducePrice().compareTo(new BigDecimal(0)) > 0 || sku.getFullPrice().compareTo(new BigDecimal(0)) > 0) {
                        couponFeign.saveSkuFullReduction(skuFullReductionTo);
                    }

                    //保存商品阶梯价格
                    SkuLadderTo skuLadderTo = new SkuLadderTo();
                    skuLadderTo.setSkuId(skuId);
                    skuLadderTo.setDiscount(sku.getDiscount());
                    skuLadderTo.setFullCount(sku.getFullCount());
                    skuLadderTo.setPrice(sku.getPrice());
                    //设置是否可以叠加其他优惠
                    skuLadderTo.setAddOther(sku.getCountStatus());

                    if (sku.getDiscount().compareTo(new BigDecimal(0)) > 0) {
                        //有折扣信息才进行保存，否则不保存
                        couponFeign.saveSkuLadder(skuLadderTo);
                    }
                    //保存会员价格
                    List<MemberPrice> memberPrice = sku.getMemberPrice();
                    if (!CollectionUtils.isEmpty(memberPrice)) {
                        List<MemberPriceTo> memberPriceTos = memberPrice.stream().map(member -> {
                            MemberPriceTo memberPriceTo = new MemberPriceTo();
                            memberPriceTo.setSkuId(skuId);
                            memberPriceTo.setAddOther(0);
                            memberPriceTo.setMemberLevelId(member.getId());
                            memberPriceTo.setMemberLevelName(member.getName());
                            memberPriceTo.setMemberPrice(member.getPrice());
                            return memberPriceTo;
                        }).collect(Collectors.toList());
                        couponFeign.saveMemberPrice(memberPriceTos);
                    }
                }
            });
        }
    }

    @Override
    public void spuUp(Long spuId) {
        //根据spuId查询所有该spu下的sku信息
        List<SkuInfoEntity> skus = skuInfoService.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
        //将所有sku的信息封装到es的数据模型中

        //es模型中的规格属性信息使用spuId通过spuAttrService查询
        List<ProductAttrValueEntity> spuAttrList = spuAttrValueService.baseAttrListForSpu(spuId);  //根据spuId查询出当前spu下的所有属性
        List<SkuEsModel.Attrs> searchAttrs = spuAttrList.stream().filter(attr -> { //遍历所有spu下的属性，根据spu属性中的attrId查询出对应的Attr后，过滤掉不需要展示的attr
            Long attrId = attr.getAttrId();
            AttrEntity attrEntity = attrService.getById(attrId);
            if (attrEntity == null) { //如果当前遍历到的attrId在Attr表中不存在，则直接过滤掉
                return false;
            }
            return attrEntity.getSearchType() != 0;
        }).map(searchAttr -> { //再将spu的attr映射成es模型中需要的attr
            SkuEsModel.Attrs attr = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(searchAttr, attr);
            return attr;
        }).collect(Collectors.toList()); //收集成list

        //是否有库存，需要通过库存服务查询
        List<Long> skuIds = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList()); //将所有的sku信息映射为skuId信息
        Map<Long, Boolean> hasStockMap; //定义一个预定的远程服务返回结果，如果调用失败，就使用null
        R res = wareFeign.hasStock(skuIds); //调用远程服务
        /*
         *
         * 调用远程服务时，返回封装的对象会封装成一个map？？？
         * 因为rpc远程调用在底层还是使用的HTTPClient，
         * 所以在传递参数的时候，必定要有个顺序，当你传递map的时候map里面的值也要有顺序，不然服务层在接的时候就出问题了，所以它才会从map转为linkedHashMap！
         * spring 有一个类叫ModelMap，继承了linkedHashMap public class ModelMap extends LinkedHashMap ,
         * 所以一个接口返回的结果就可以直接用ModelMap来接，注意ModelMap是没有泛型的，不管你返回的结果是什么类型的map，泛型是多复杂的map，都可以直接new一个ModelMap，
         * 用它来接返回的结果！！！
         * */
        /*System.out.println(res);
        List<Map<String, Object>> hasStock = (List<Map<String, Object>>) res.get("hasStock");


        System.out.println(hasStock);
        List<SkuHasStockVo> skuHasStockVoList = new ArrayList<>();

        for (Map<String, Object> map : hasStock) {
            Integer key = (Integer) map.get("skuId");
            Boolean value = (Boolean) map.get("hasStock");
            SkuHasStockVo skuHasStockVo = new SkuHasStockVo();
            skuHasStockVo.setSkuId(key.longValue());
            skuHasStockVo.setHasStock(value);
            skuHasStockVoList.add(skuHasStockVo);
        }*/

        List<SkuHasStockVo> skuHasStockVoList = res.getData(new TypeReference<List<SkuHasStockVo>>() {});
        System.out.println(skuHasStockVoList);
        hasStockMap = skuHasStockVoList.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock));


        Map<Long, Boolean> finalHasStockMap = hasStockMap;

        //封装es模型信息
        List<SkuEsModel> esModelList = skus.stream().map((sku) -> {
            SkuEsModel skuEsModel = new SkuEsModel();
            //使用工具类拷贝相同的数据
            BeanUtils.copyProperties(sku, skuEsModel);
            /*
             * 不同的数据需要手动设置：
             * skuPrice,skuImg,
             *
             * hasStock, hotScore
             *
             * brandName,brandImg,catalogName
             *
             * attrs
             *      attrId,attrName,attrValue
             */
            skuEsModel.setSkuPrice(sku.getPrice());
            skuEsModel.setSkuImg(sku.getSkuDefaultImg());

            //是否有库存，需要通过库存服务查询
            /*R response = wareFeign.skuInfo(sku.getSkuId());
            Boolean hasStock = (Boolean) response.get("hasStock");
            skuEsModel.setHasStock(hasStock);*/
            if (CollectionUtils.isEmpty(finalHasStockMap)) {
                skuEsModel.setHasStock(false);
            } else {
                Long skuId = sku.getSkuId();
                System.out.println(skuId.getClass());

                Boolean b = finalHasStockMap.get(skuId);
                skuEsModel.setHasStock(b);

                if (skuEsModel.getHasStock() == null) {
                    System.out.println("设置失败");
                } else {
                    System.out.println("设置成功");
                }
            }

            //热度评分默认设置0
            skuEsModel.setHotScore(0L);

            //品牌信息通过brandService直接查询
            Long brandId = sku.getBrandId();
            BrandEntity brandEntity = brandService.getById(brandId);
            skuEsModel.setBrandId(brandId);
            skuEsModel.setBrandImg(brandEntity.getLogo());
            skuEsModel.setBrandName(brandEntity.getName());


            // catalog的id和name没有设置。重大失误
            Long catalogId = sku.getCatalogId();
            skuEsModel.setCatalogId(catalogId);
            skuEsModel.setCatalogName(categoryService.getById(catalogId).getName());

            /*List<SkuEsModel.Attrs> attrList = new ArrayList<>();
            searchAttrs.forEach(searchAttr -> {
                SkuEsModel.Attrs attr = new SkuEsModel.Attrs();
                BeanUtils.copyProperties(searchAttr, attr);
                attrList.add(attr);
            });*/

            skuEsModel.setAttrs(searchAttrs);

            return skuEsModel;
        }).collect(Collectors.toList());

        //将封装好的es数据交给远程搜索服务保存
        try {
            R r = searchFeign.productSearchSave(esModelList);
            if ((Integer) r.get("code") == 0) {
                //将spu的状态修改为已上架
                UpdateWrapper<SpuInfoEntity> updateWrapper = new UpdateWrapper<>();
                updateWrapper.set("publish_status", ProductConstant.SpuStatus.UP.getCode()); //报错：忘记getCode
                updateWrapper.set("update_time", new Date());
                baseMapper.update(this.getById(spuId), updateWrapper);
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }


    }

}